package com.lzx.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

public class DownloadAction extends DispatchAction {

	// 实现文件的下载
	public ActionForward downFile(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String path = request.getParameter("path");
		System.out.println(path + "111");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		OutputStream fos = null;
		InputStream fis = null;

		// 如果是从服务器上取就用这个获得系统的绝对路径方法。

		String filepath = this.servlet.getServletContext().getRealPath("/");
		String fileName = "a.txt";

		System.out.println("文件路径" + filepath + fileName);
		File uploadFile = new File(filepath, fileName);
		fis = new FileInputStream(uploadFile);
		bis = new BufferedInputStream(fis);
		fos = response.getOutputStream();
		bos = new BufferedOutputStream(fos);

		// 这个就就是弹出下载对话框的关键代码
		response.setHeader("Content-disposition", "attachment;filename="
				+ URLEncoder.encode(fileName, "utf-8"));

		int bytesRead = 0;
		// 这个地方的同上传的一样。我就不多说了，都是用输入流进行先读，然后用输出流去写，唯一不同的是我用的是缓冲输入输出流
		byte[] buffer = new byte[8192];
		while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
			bos.write(buffer, 0, bytesRead);
		}
		bos.flush();
		fis.close();
		bis.close();
		fos.close();
		bos.close();
		return null;
	}

	public ActionForward downFile2(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		response.setContentType("application/x-download");// 设置为下载
		String filenamedownload = this.servlet.getServletContext().getRealPath(
				"/news");// 即将下载的文件的相对路径
		String filenamedisplay = "a.txt";// 下载文件时显示的文件保存名称
		filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
		response.addHeader("Content-Disposition", "attachment;filename="
				+ filenamedisplay);

		try {

			RequestDispatcher dispatcher = this.getServlet()
					.getServletContext().getRequestDispatcher(
							"/R:/upload/a.txt");
			if (dispatcher != null) {
				dispatcher.forward(request, response);
			}
			response.flushBuffer();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			return null;
		}

	}

}
